package cn.da.shuai.cool.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.spec.KeySpec;
import java.util.Base64;

public class DESedeUtil {

    private static final String ALGORITHM = "DESede"; // 3DES算法

    public static String encrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, SecretKeyHolder.SECRET_KEY);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to encrypt data", e);
        }
    }

    public static String decrypt(String encryptedData) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, SecretKeyHolder.SECRET_KEY);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to decrypt data", e);
        }
    }

    private static class SecretKeyHolder {
        private static final SecretKey SECRET_KEY;
        static {
            try {
                String keyString = "4203ruCT3440-NVT9Vfe223T34CFWE"; // 24字节的密钥
                byte[] keyBytes = keyString.getBytes();
                KeySpec keySpec = new DESedeKeySpec(keyBytes);
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
                SECRET_KEY = keyFactory.generateSecret(keySpec);
            } catch (Exception e) {
                throw new RuntimeException("Failed to initialize 3DES key", e);
            }
        }
    }
}
